import {Injectable} from '@angular/core';
import {Hero} from "./hero";
import {HEROES} from "./mock-heroes";
import {Observable, of} from 'rxjs';
import {MessageService} from './message.service';

//@Injectable() 装饰器会接受该服务的元数据对象，就像 @Component() 对组件类的作用一样。
@Injectable({
  providedIn: 'root'
})
export class HeroService {

  constructor(private messageService: MessageService) {
  }

  //模拟同步
  // getHeroes(): Hero[] {
  //   return HEROES;
  // }


  //模拟异步
  getHeroes(): Observable<Hero[]> {
    this.messageService.add('HeroService: 获取英雄数据完成！');
    return of(HEROES);
  }

  getHero(id: number): Observable<Hero> {
    // For now, assume that a hero with the specified `id` always exists.
    // Error handling will be added in the next step of the tutorial.
    const hero = HEROES.find(h => h.id === id)!;
    this.messageService.add(`HeroService: 目标英雄id为 ${id}`);
    return of(hero);
  }
}
